package com.ark.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.ark.yygh.common.helper.JwtHelper;
import com.ark.yygh.common.result.Result;
import com.ark.yygh.model.user.UserInfo;
import com.ark.yygh.user.service.UserInfoService;
import com.ark.yygh.user.utils.ConstantWxPropertiesUtil;
import com.ark.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信操作接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("获取生成微信二维码，微信登录参数")
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope","snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL;
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl,"UTF-8");
            map.put("redirect_uri","snsapi_login");
            map.put("redirect_uri",wxOpenRedirectUrl);
            map.put("state",System.currentTimeMillis()+"");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    @ApiOperation("回调方法  得到扫描人的信息")
    @GetMapping("/callback")
    public String callback(String code,String state){
        //1、获取临时票据 code
        System.out.println("code:"+code);
        //2、通过code加上appid和lappsecret换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        //使用 httpClient 请求地址
        try {
            String s = HttpClientUtils.get(accessTokenUrl);
            System.out.println("s = " + s);
            //在s这个字符串中  获取  openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(s);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //判断数据是否存在微信扫描人的信息  根据openid判断
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if (userInfo == null){
                //微信用户不存在
                //拿着openid和access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo:"+resultInfo);

                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);

                //解析用户
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //获取扫码人信息 添加数据库
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)){
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)){
                name = userInfo.getPhone();
            }
            map.put("name",name);
            if (StringUtils.isEmpty(userInfo.getPhone())){
                map.put("openid",userInfo.getOpenid());
            }else {
                map.put("openid","");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);

            //跳转到前端
            return
                    "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL +
                            "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+
                            "&name="+URLEncoder.encode(map.get("name"),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
